package com.myzf.ncov.utils;

import com.sun.glass.events.KeyEvent;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.lang.reflect.Field;

/**
 * 发送消息工具类
 *
 * @author limuyi
 * @version V1.0
 * Created by limuyi on 2020-02-01 15:59
 */
@Slf4j
public class SendMessageUtil {

    private static Robot robot;

    static {
        try {
            robot = new Robot();
        } catch (AWTException e) {
            log.error(e.getLocalizedMessage());
        }
    }

    /**
     * 赋值键
     *
     * @param text 文本
     */
    private static void copy(String text) {
        Clipboard sysc = Toolkit.getDefaultToolkit().
                getSystemClipboard();
        Transferable tText = new StringSelection(text);
        sysc.setContents(tText, null);
    }


    /**
     * ctrl组合键
     *
     * @param key 按键名
     */
    private static void sendCtrlWith(String key) {
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            log.error(e.getLocalizedMessage());
        }
        robot.keyPress(KeyEvent.VK_CONTROL);
        sendKey(key);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }

    /**
     * 执行键位
     *
     * @param key 按键名
     */
    private static void sendKey(String key) {
        try {
            String KeyName = (key + "").toUpperCase();
            Field f = KeyEvent.class.getDeclaredField("VK_" + KeyName);
            Object o = f.get(null);
            int keyCode = Integer.parseInt(o + "");
            robot.keyPress(keyCode);
            robot.keyRelease(keyCode);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
        }
    }

    /**
     * 发送消息
     *
     * @param message    消息
     * @param windowName 程序名
     */
    public static void sendMessage(String message, String className, String windowName) {
        WinDef.HWND hwnd = User32.INSTANCE.FindWindow(className, windowName);
        if (hwnd == null) {
            log.error("### " + windowName + " is not running ###");
        } else {
            User32.INSTANCE.ShowWindow(hwnd, WinUser.SW_RESTORE);
            User32.INSTANCE.SetForegroundWindow(hwnd);   // bring to front

            copy(message);
            sendCtrlWith("v");
            sendCtrlWith("Enter");
        }
    }
}
